/**
 * 全局使用方法
 * this.$toast(option)
 * option: String|Number|Object
 * {
 *  content: String|Number, //显示内容
 *  time: Numer // 毫秒
 * }
 *
 */

import Vue from 'vue'
import ToastCom from './toast.vue'

const ToastConstructor = Vue.extend(ToastCom)

// 创建组件对象
let instance = null
let timer = null

// 导出方法
const toastFun = function (opt) {
  let option = {
    content: opt,
    time: 3000
  }
  if (typeof opt === 'object') {
    option = {
      content: '',
      time: 3000,
      ...(opt || {})
    }
  }
  const id = 'toast__global'

  if (instance) {
    instance.close()
    clearTimeout(timer)
    timer = null
  }
  // 关闭方法
  instance = new ToastConstructor({
    data: option
  })

  instance.id = id
  instance.$mount()
  document.body.appendChild(instance.$el)
  instance.visible = true
  instance.dom = instance.$el
  instance.dom.style.zIndex = 9999

  timer = setTimeout(() => {
    instance.close()
    instance = null
  }, option.time)
}

export default toastFun
